<template>
  <el-cascader
    v-model="addressIds"
    :disabled="disabled"
    :props="areas"
    class="w-full"
    placeholder="请选择所属区域"
    @change="areaChange"
  />
</template>

<script>
export default {
  name: "Areas",

  // 接收 province_id、city_id、county_id
  props: {
    ids: {
      type: Array,
      default: () => []
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      addressIds: [],
      selectValues: [1],
      country_id: "",
      options: [],
      areas: {
        lazy: true,
        lazyLoad: (node, resolve) => {
          this.getLocalisationCountries().then(() => {
            this.getArea(node, resolve);
          });
        }
      }
    };
  },

  mounted() {
    this.addressIds = this.ids
  },

  methods: {
    // 获取国家
    async getLocalisationCountries() {


      // const loading = this.$loading({lock: true});
      // this.$http.post('/level/delete'}).then(res => {
      //   loading.close();
      //   if (res.data.code === 0) {
      //     this.$message.success(res.data.msg);
      //     this.reload();
      //   } else {
      //     this.$message.error(res.data.msg);
      //   }
      // }).catch(e => {
      //   loading.close();
      //   this.$message.error(e.message);
      // });
      await this.$http.get("/city/index").then((res) => {
        this.country_id = res.data.find((e) => e.name === "中国").id;
      });
    },

    // 省市县三级联动
    getArea(node, resolve) {
      const { level } = node;
      if (level === 0) {
        this.$http
          .get(`/city/index/${this.country_id}`)
          .then((res) => {
            resolve(this.formatAreaData(res.data.provinces, level));
          });
      } else if (level === 1) {
        this.$http
          .get(`/city/index/${node.data.value}`)
          .then((res) => {
            resolve(this.formatAreaData(res.data.cities, level));
          });
      } else if (level === 2) {
        this.$http.get(`/city/index/${node.data.value}`).then((res) => {
          resolve(this.formatAreaData(res.data.counties, level));
        });
      }
    },

    // 格式化三级联动数据
    formatAreaData(data, level) {
      return data.map((item) => {
        return {
          value: item.id,
          label: item.name,
          leaf: level >= 2
        };
      });
    },

    areaChange(value) {
      this.$emit("areaChange", [this.country_id, ...value]);
    }
  }
};
</script>
